package com.example.ibsp_demo.controller.login.email;

import com.example.ibsp_demo.mapper.user.UserMapper;
import com.example.ibsp_demo.pojo.response.ResponseMessage;
import com.example.ibsp_demo.service.IVerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/email/auth")
public class AuthController {

    @Autowired
    private IVerificationCodeService codeService;

    @Autowired
    private UserMapper userMapper;
    /**
     * 发送邮箱验证码
     * @param email 邮箱地址
     */
    @PostMapping("/sendCode")
    public ResponseMessage sendVerificationCode(@RequestParam String email,@RequestParam String typeCode) {
        // 是否绑定用户
        if(userMapper.selectByEmail(email) == null && typeCode.equals("reset")){
            return ResponseMessage.error(2004,"该邮箱未绑定用户");
        }
        if(userMapper.selectByEmail(email) != null && typeCode.equals("register")){
            return ResponseMessage.error(2005,"该邮箱已被注册");
        }
        if("".equals(typeCode)){
            return ResponseMessage.error(2007,"未指定验证码类型");
        }

        // 验证邮箱格式
        if (!isValidEmail(email)) {
            return ResponseMessage.error(2001,"邮箱格式不正确");
        }

        // 检查是否频繁发送
        if (isFrequentRequest(email)) {
            return ResponseMessage.error(2002,"发送过于频繁，请稍后再试");
        }

        try {
            //发送
            return ResponseMessage.success(codeService.sendVerificationCode(email,typeCode));
        } catch (Exception e) {
            return ResponseMessage.error(2003,"发送失败，请稍后再试");
        }
    }

    // 邮箱格式验证
    private boolean isValidEmail(String email) {
        //当我真的想得到验证码时一定会输入一个格式正确的验证码
        //当我只是想测试发送验证码的功能时，我就输入一个错误的格式
        return email != null && email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
    }

    // 检查请求频率（可使用Redis实现）
    private boolean isFrequentRequest(String email) {
        // 实现逻辑略，可通过Redis记录发送时间
        return false;
    }
}